<template>
  <div>

    <!--    &lt;!&ndash;面包屑导航&ndash;&gt;-->
    <!--    <el-breadcrumb separator="/">-->
    <!--      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>-->
    <!--      <el-breadcrumb-item>权限管理</el-breadcrumb-item>-->
    <!--      <el-breadcrumb-item>用户管理</el-breadcrumb-item>-->
    <!--    </el-breadcrumb>-->


    <el-card>
      <el-row :gutter="20">

        <!--用户搜索框-->
        <el-col :span="8">
          <el-input placeholder="请输用户名称" clearable v-model="keyword">
            <el-button slot="append" icon="el-icon-search" @click="initManagerList"></el-button>
          </el-input>
        </el-col>

        <!--添加用户按钮-->
        <el-col :span="4">
          <el-button type="primary" @click="showAddForm">添加用户</el-button>
        </el-col>

      </el-row>

      <!--显示用户搜索结果项列表-->
      <el-table :data="managerList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="用户密码">******</el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="success" size="mini" @click="showManagerConfigRoleForm(scope.row)">赋予角色</el-button>
            <el-button type="warning" size="mini" @click.prevent="showUpdateForm(scope.row)">修改</el-button>
            <el-button type="danger" size="mini" @click.prevent="resetPassword(scope.row.userId)">重置密码</el-button>
            <el-button type="danger" size="mini" @click.prevent="del(scope.row.userId)">删除</el-button>

          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

    </el-card>


    <!--添加用户对话框-->
    <el-dialog title="添加用户" :visible.sync="addFormVisible" @close="closeAddForm" :close-on-click-modal="false">

      <!--具体表单-->
      <el-form ref="addForm" :rules="addManagerRules" :model="addManager" label-width="150px" size="mini">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="addManager.username"></el-input>
        </el-form-item>

        <el-form-item label="用户密码" prop="password">
          <el-input v-model="addManager.password"></el-input>
        </el-form-item>

        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="addManager.phoneNumber"></el-input>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddForm">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>

    </el-dialog>


    <!--修改用户对话框-->
    <el-dialog title="修改用户" :visible.sync="updateFormVisible" @close="closeUpdateForm"
               :close-on-click-modal="false">

      <!--具体表单-->
      <el-form ref="updateForm"  :model="updateManager" label-width="150px" size="mini">

        <el-form-item label="用户名称" prop="username">
          <el-input v-model="updateManager.username"></el-input>
        </el-form-item>

        <el-form-item label="用户手机号" prop="phoneNumber">
          <el-input v-model="updateManager.phoneNumber"></el-input>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeUpdateForm">取 消</el-button>
        <el-button type="primary" @click="submitupdateForm">确 定</el-button>
      </div>

    </el-dialog>

    <!--管理员配置角色对话框-->
    <el-dialog title="管理员配置角色" :visible.sync="configRoleVisible" @close="closeConfigForm"
               :close-on-click-modal="false">

      <!--具体表单-->
      <el-form ref="configRoleForm" :model="configRole" label-width="150px" size="mini">

        <el-form-item label="管理员名称" prop="username">
          <el-input v-model="configRole.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="选择角色" prop="permission">
          <el-select v-model="configRole.permission"  placeholder="请选择角色">
            <el-option
                v-for="item in roleOptions"
                :key="item.userId"
                :label="item.name"
                :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeConfigForm">取 消</el-button>
        <el-button type="primary" @click="submitConfigForm">确 定</el-button>
      </div>

    </el-dialog>


  </div>

</template>

<script>
export default {
  name: "ManagerList",
  data() {
    return {
      keyword: "", //要搜索的用户名称
      managerList: [], //用户搜索结果
      currentPage: 1,
      pageSize: 5,
      total: 0,
      //添加用户相关
      addFormVisible: false,
      addManagerRules: {
        username: [
          {required: true, message: "用户名不能为空", trigger: "blur"}
        ],
        password: [
          {required: true, message: "密码不能为空", trigger: "blur"},
          { min: 8, max: 20, message: "密码在8到20个字符之间", trigger: "blur" }
        ],
        phoneNumber: [
          {required: true, message: "手机号码不能为空", trigger: "blur"},
          {min: 11, max: 11, message: "手机号格式错误,请检查!", trigger: "blur"}
        ],
      },
      addManager: {
        username: '',
        password: '',
        phoneNumber: ''
      },
      //修改用户相关
      updateFormVisible: false,
      updateManager: {
        userId: 0,
        username: '',
        phoneNumber: ''
      },
      //配置角色相关
      configRoleVisible: false,
      configRole: {
        userId: 0,
        username: 'xxx',
        permission: 0 //用户选取的角色
      },
      roleOptions: [{userId: 0, name: "管理员"}, {userId: 1, name: "讲师"},{userId: 2, name: "学生"}],  //全部的角色


    };
  },
  methods: {
    // 初始化列表
    initManagerList() {

      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      }

      this.$axios.postForm("/userinfo/selectUserInfo", params)
          .then(response => {
            let responseData = response.data;
            console.log(responseData)
            console.log(responseData.records)

            this.managerList = responseData.records;
            this.currentPage = responseData.current;
            this.pageSize = responseData.size;
            this.total = responseData.total;

          })
    }
    ,
    //页面展示条数方法
    handleSizeChange(size) {
      this.currentPage = 1;
      this.pageSize = size;
      this.initManagerList();
    }
    ,
    //第几页方法
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.initManagerList();
    }
    ,
    // 添加显示添加框
    showAddForm() {
      this.addFormVisible = true;
    }
    ,
    //关闭添加框
    closeAddForm() {
      this.addFormVisible = false;
      this.$refs.addForm.resetFields();
    }
    ,
    //添加提交框
    submitAddForm() {
      this.$refs.addForm.validate(isValid => {
        //表单校验
        if (!isValid) {
          this.$message({
            message: "请正确填写表单",
            type: 'error',
            duration: 2000
          })
          return;
        }

        for (let i=0; i< this.managerList.length;i++) {
          if(this.addManager.phoneNumber == this.managerList[i].phoneNumber){
            console.log("这里是手机号")
          console.log(this.managerList[i].phoneNumber)
          this.$message({
            message : "当前手机号已被注册",
            type : "error",
            duration : 2000
          })
          return;
          }
        }

        this.$axios.post("/userinfo/addUser", this.addManager)
            .then(response => {
              console.log(response);

              if (response.status === 200) {
                this.$message({
                  message: "添加成功",
                  type: 'success',
                  duration: 2000
                })
                this.closeAddForm();
              } else {
                this.$message({
                  message: "添加用户失败",
                  type: 'error',
                  duration: 2000
                })
              }
              this.initManagerList()
            })

      })
    }
    ,
    //修改用户相关
    showUpdateForm(manager) {
      console.log(manager)

      this.updateManager.userId = manager.userId;
      this.updateManager.username = manager.username;
      this.updateManager.phoneNumber = manager.phoneNumber;

      this.updateFormVisible = true;
    }
    ,
    closeUpdateForm() {
      this.updateFormVisible = false;
      this.$refs.updateForm.resetFields();
    }
    ,
    submitupdateForm() {
      this.$refs.updateForm.validate(isValid => {

        //表单校验
        if (!isValid) {
          this.$message({
            message: "请正确填写表单",
            type: 'error',
            duration: 2000
          })
          return;
        }

        for (let i=0; i< this.managerList.length;i++) {
          if(this.addManager.phoneNumber == this.managerList[i].phoneNumber){
            this.$message({
              message : "当前手机号已被注册",
              type : "error",
              duration : 2000
            })
          return;
          }
        }

        console.log(this.updateManager)

        this.$axios.postForm("userinfo/updateUserInfo", this.updateManager)
            .then(response => {
              if (response.status === 200) {
                this.$message({
                  message: "修改成功",
                  type: 'success',
                  duration: 2000
                })
                this.closeUpdateForm();

                //刷新当前页数据
                this.initManagerList()
              } else {
                this.$message({
                  message: "修改失败",
                  type: 'error',
                  duration: 2000
                })
              }

            })
            .catch(error => {
              console.log(error)
            })

      })

    }
    ,
    // 删除
    del(userId) {
      console.log(userId);
      const pam = {
        userId: userId
      };
      this.$confirm('此操作将永久删除该用户,是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //确定

        this.$axios.postForm("userinfo/deleteUser",pam)
            .then(response => {

              if (response.status === 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                  duration: 2000
                });

                //刷新当前页
                this.initManagerList();

              } else {
                this.$message({
                  type: 'error',
                  message: "删除失败",
                  duration: 2000
                });
              }

            })

      }).catch(() => {
        //取消
        this.$message({
          type: 'success',
          message: '已取消删除'
        });
      })

    },

    //resetPassword 重置密码
    resetPassword(userId){

      console.log(userId)
      const pam = {
        userId: userId
      };
      this.$confirm('此操作会将用户密码重置为初始密码,是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //确定

        this.$axios.postForm("userinfo/resetPassword",pam)
            .then(response => {

              if (response.status === 200) {
                this.$message({
                  type: 'success',
                  message: '重置成功!',
                  duration: 2000
                });

                //刷新当前页
                this.initManagerList();

              } else {
                this.$message({
                  type: 'error',
                  message: "重置失败",
                  duration: 2000
                });
              }

            })

      }).catch(() => {
        //取消
        this.$message({
          type: 'success',
          message: '已取消'
        });
      })
    },

    // 获取当前用户的角色
    getThisRole(userId) {
      this.$axios.postForm("userinfo/getThisRole", {userId: userId})
          .then(res => {
        if (res.status === 200) {
          this.configRole.permission = res.data.permission;
          console.log(this.configRole.permission)
        }
      })
    },

    //配置角色相关
    showManagerConfigRoleForm(manager) {
      this.configRole.userId = manager.userId
      this.configRole.username = manager.username


      this.getThisRole(manager.userId);

      console.log(manager)

      this.configRoleVisible = true;
    }
    ,
    closeConfigForm() {
      this.configRole.roleIds = []
      this.configRoleVisible = false;
    }
    ,
    submitConfigForm() {
      console.log(this.configRole)
      this.$axios.postForm("/userinfo/personalize", this.configRole)
          .then(res => {
            console.log(res)
        if (res.status === 200) {
          this.$message({
            message: "配置成功",
            type: "success",
            duration: 2000
          })
        } else {
          this.$message({
            message: "赋予角色失败",
            type: "error",
            duration: 2000
          })
        }
      })
      this.closeConfigForm();
    }
  },
  created() {
    this.initManagerList();
  }

}
</script>

<style scoped>

</style>